//
//  SeekCarViewController.m
//  myCar
//
//  Created by 刘莉 on 14-10-27.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "SeekCarViewController.h"
#import "MineViewController.h"
#import "AIMTableViewIndexBar.h"
#import "BrandCarCell.h"
#import "HotCell.h"
#import "UIImageView+WebCache.h"
#import "MySecion.h"
#import "CollectionCell.h"
#import "MyCar.h"
#import "Car.h"
#import "ExactCarController.h"
#import "ExaxtCar.h"
#import "CarValueCell.h"
#import "SearchViewController.h"
#import "HttpViewController.h"
#import "AFNetworking.h"
#import "WebColor.h"
#import "MBProgressHUD.h"
#import "WebColor.h"
@interface SeekCarViewController ()<UITableViewDataSource, UITableViewDelegate, AIMTableViewIndexBarDelegate, UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate>

@property (nonatomic, retain) UIButton           *switchButton; // 点击汽车详情会隐藏的页面
@property (nonatomic, retain) UIButton           *passButton; // 显示有多少款车符合条件，点击进入详情
@property (nonatomic, retain) NSString           *hotSerial;  // 热门车系里的车品牌
@property (nonatomic, retain) NSString           *modelTotal; // 一共有多少个符合条件的汽车类型
@property (nonatomic, retain) UIScrollView       *scrollView;
@property (nonatomic, retain) UITableView        *tableView;
@property (nonatomic, retain) UITableView        *exactTable; // 显示车的价格
@property (nonatomic, retain) UISegmentedControl *segment; //  精准选车 和品牌选车的、
@property (nonatomic, retain) UICollectionView   *collectionView; //   显示车的各种选项的collectionView
@property (nonatomic, retain) NSMutableArray     *indexArr;  // 字母数组
@property (nonatomic, retain) NSMutableArray     *rowNumArr; // 每个字母下的车型个数数组 如A: 奥迪，AC宝马共五个。
@property (nonatomic, retain) NSMutableArray     *brandArr;  // 车牌数组 存的字典 A： 奥迪 B： 宝马
@property (nonatomic, retain) NSMutableArray     *criterionArr; // 所有车的标准数组 （0 － 5 ）
@property (nonatomic, retain) NSMutableArray     *collectionSection; //section数组 保存section 如价格
@property (nonatomic, retain) NSMutableArray     *collectionClass;// 里面保存的时所有车的标准
@property (nonatomic, retain) NSMutableArray     *valueArr; // 记录被选中的类别的value值
@property (nonatomic, retain) NSMutableArray     *modelArr;
@property (nonatomic, retain) NSMutableArray     *carValueArr;// 记录品牌选车下选择一个品牌下 其子类的报价
@property (nonatomic, retain) NSMutableArray     *collectionIndexPathArr;// 记录当前点击的cell的位置  如果没有点击则默认为(0, 0) , (0, 1), (0 , 2), (0 , 3)
@property (nonatomic, retain) AIMTableViewIndexBar *indexBar; //  索引ABC
@end

@implementation SeekCarViewController


- (void)dealloc
{
    [_criterionArr release];
    [_scrollView release];
    [_segment    release];
    [_tableView  release];
    [_indexArr   release];
    [_indexBar   release];
    [_rowNumArr  release];
    [_carValueArr release];
    [_brandArr   release];
    [_hotSerial  release];
    [_collectionView release];
    [_collectionSection release];
    [_collectionClass  release];
    [_collectionIndexPathArr release];
    [_switchButton  release];
    [_exactTable    release];
    
    [super       dealloc];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.indexArr   = [NSMutableArray array];
        self.rowNumArr  = [NSMutableArray array];
        self.brandArr   = [NSMutableArray array];
        self.collectionSection = [NSMutableArray array];
        self.collectionClass   = [NSMutableArray array];
        self.criterionArr      = [NSMutableArray array];
        self.modelArr          = [NSMutableArray array];
        self.carValueArr = [NSMutableArray array];
        
        
        
        
    }
    return self;
}

- (void)initPathAndValue
{
    self.collectionIndexPathArr = [NSMutableArray array];
    self.valueArr  = [NSMutableArray array];
    
    for (int i = 0; i  < 4; i++) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:i];
        [self.collectionIndexPathArr addObject:indexPath];
        NSString *str = self.collectionSection[i];// collectioncell 的字符串
        MyCar *car = [self.collectionClass[i] valueForKey:str][indexPath.item];
    
        // 符合搜索的条件的车
        [self.valueArr addObject:car.value];
    }
    
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"找车";
    [self startConnection];
    [self setupSubViews];
    
}
// 网络解析


- (void)startConnection
{
    MBProgressHUD *hub = [[MBProgressHUD alloc] init];
    [hub setMode:MBProgressHUDModeIndeterminate];
    [hub show:YES];
    [self.view addSubview:hub];
    NSString *str = @"http://mrobot.pcauto.com.cn/v2/price/brands?v=4.0.0";
    AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
    [manager1.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    [manager1 GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *sectionArr = [responseObject objectForKey:@"sections"];
        for (NSDictionary *dic in sectionArr) {
            [self.indexArr addObject:[dic objectForKey:@"index"]];
            [self.rowNumArr addObject:[dic objectForKey:@"rowNum"]];
            for (NSDictionary *brandDic in [dic objectForKey:@"brands"]) {
                if ([[brandDic allKeys]containsObject:@"hotSerial"]) {
                    self.hotSerial = [brandDic objectForKey:@"hotSerial"];
                }
                Car *car = [[Car alloc]initWithDictionary:brandDic];
                [self.brandArr addObject:car];
                [car release];
                
            }
        }
        
        self.indexBar = [[AIMTableViewIndexBar alloc]initWithFrame:CGRectMake(self.view.bounds.size.width - 20, 0, 20, self.view.bounds.size.height - 64 - 49)];
        self.indexBar.delegate = self;
        [self.scrollView addSubview:self.indexBar];
       
        [self.indexBar setIndexes:self.indexArr];
        [self.tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 120, 280, 100)];
        imageView.image = [UIImage imageNamed:@"poNet.jpg"];
        self.tableView.backgroundView = imageView;
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起暂无网络" message:@"请返回" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil];
        [alertView show];
    }];
    
    NSString *collectionUrl  = @"http://mrobot.pcauto.com.cn/v3/price/models/criterionv36?v=4.3.0";
    
    AFHTTPRequestOperationManager *manager2 = [AFHTTPRequestOperationManager manager];
    
    [manager2.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    
    [manager2 GET:collectionUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *arr = [responseObject objectForKey:@"criterion"];
        for (int i = 0; i < 4; i++) {
            NSDictionary *dic = arr[i];
            [self.collectionSection addObject:[dic objectForKey:@"name"]];
            NSMutableArray *totalArr = [NSMutableArray array]; // cris 字典下的
            NSArray *crisArr = [dic  objectForKey:@"cris"];
            for (NSDictionary *dicCris in crisArr) {
                MyCar *myCar = [[MyCar alloc]initWithDictionary:dicCris];
                [totalArr addObject:myCar];
            }
            NSMutableDictionary *dicName = [NSMutableDictionary dictionaryWithObject:totalArr forKey:[dic objectForKey:@"name"]];
            [self.collectionClass addObject:dicName];
            
        }
        
        [self initPathAndValue];
        [self.collectionView reloadData];
        [hub removeFromSuperview];
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     }];
}

#pragma mark tableView 协议
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.exactTable) {
        return 80;
    }
    return 70;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == self.tableView) {
        return self.indexArr.count;
    }
    return self.carValueArr.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
    return self.indexArr[section];
    }
    return [self.carValueArr[section] allKeys][0];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableView) {
        if (section == 0) {
            return 1;
        } else {
            return [self.rowNumArr[section]integerValue];
        }
    }
    
    NSArray *arr = [self.carValueArr[section] objectForKey:[self.carValueArr[section] allKeys][0]];
    return arr.count;
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        int n = 0; // 记录当前cell 在brandArr的位置
        for (int i = 0; i < indexPath.section; i++) {
            n += [self.rowNumArr[i] integerValue];
        }
        
        if (indexPath.section != 0) {
            BrandCarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"seek"];
            cell.car = self.brandArr[indexPath.row + n  + 1];
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 60)];
            imageView.image = [UIImage imageNamed:@"cellbg.jpg"];
            cell.backgroundView = imageView;
            return cell;
        }
        HotCell *cell = [tableView dequeueReusableCellWithIdentifier:@"hot"];
        
        Car *car = self.brandArr[0];
        [cell.hotImgView setImageWithURL:[NSURL URLWithString:car.logo]];
        cell.hotLabel.text = car.name;
        cell.nameLabel.text = self.hotSerial;
        cell.selectionStyle = 0;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 60)];
        imageView.image = [UIImage imageNamed:@"cellbg.jpg"];
        cell.backgroundView = imageView;
        return cell;
        
    }
    CarValueCell *cell = [tableView dequeueReusableCellWithIdentifier:@"value"];
    NSString *str = [self.carValueArr[indexPath.section] allKeys][0];
    ExaxtCar *car = [self.carValueArr[indexPath.section] objectForKey:str][indexPath.row];
    cell.car = car;
    
    cell.newLabel.backgroundColor = [UIColor clearColor];
    cell.newLabel.text = nil;
    if ([car.isNew isEqual:@1]) {
        
        cell.newLabel.backgroundColor = [UIColor redColor];
        cell.newLabel.text = @"新车上市";
    }
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 60)];
    imageView.image = [UIImage imageNamed:@"cellbg.jpg"];
    cell.backgroundView = imageView;
    return cell;
    
    
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableView) {
        int n = 0; // 记录当前cell 在brandArr的位置
        for (int i = 0; i < indexPath.section; i++) {
            n += [self.rowNumArr[i] integerValue];
        }
        
        NSMutableString *urlStr = [NSMutableString string];// 记录汽车的id的变量
        
        [self.carValueArr removeAllObjects];
       
        
        if (indexPath.section != 0) {
            
            Car *car = self.brandArr[indexPath.row + n + 1];
            [urlStr appendFormat:@"http://mrobot.pcauto.com.cn/v3/price/getSerialListByBrandId/%@", car.idNum ];
            [self startCarValueConnectionwithUrl:urlStr];
        } else {
            [urlStr appendFormat:@"%@",@"http://mrobot.pcauto.com.cn/configs/pcauto_hot_serials" ];
            [self hotConnectionWithStr:urlStr];
        }
        
        
    } else
    {
        NSString *str = [self.carValueArr[indexPath.section] allKeys][0];
        ExaxtCar *car = [self.carValueArr[indexPath.section] objectForKey:str][indexPath.row];
       
        
        [self localSave:car];
        HttpViewController *httpVC = [[HttpViewController alloc]init];
        httpVC.car = car;
       
        [self.navigationController pushViewController:httpVC animated:YES];
        [httpVC release];
    }
}

- (void)localSave:(ExaxtCar *)myCar
{
    
    
    NSString *cachesPath  = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *arrPath = [cachesPath stringByAppendingPathComponent:@"seekCar.plist"];
   
    NSArray *arr = [NSKeyedUnarchiver unarchiveObjectWithFile:arrPath];
    
    if (arr == nil) {
        NSMutableArray *arrSave = [NSMutableArray arrayWithObject:myCar];
        [NSKeyedArchiver archiveRootObject:arrSave toFile:arrPath];
        
    } else {
        NSMutableArray *saveArr = [NSMutableArray arrayWithArray:arr];
        
        
        if (saveArr.count == 4) {
            [saveArr removeObjectAtIndex:0];
        }
        
        for (ExaxtCar * car in saveArr) {
            if ([car.serialName isEqualToString:myCar.serialName]) {
                [saveArr removeObject:car];
                break;
            }
        }
        [saveArr addObject:myCar];
        [NSKeyedArchiver archiveRootObject:saveArr toFile:arrPath];
       
    }
    
    
}


#pragma mark - 解析车的具体价格
/// 热门
- (void)hotConnectionWithStr:(NSString *)str
{

   
        AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
        
        [manager1.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
        
        [manager1 GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            NSArray *arr = [[[responseObject objectForKey:@"manufacturers"] firstObject] objectForKey:@"serials"];
            for (NSDictionary *dic in arr) {
                ExaxtCar *car = [[ExaxtCar alloc]initWithDictionary:dic];
                if ([[[self.carValueArr lastObject] allKeys] containsObject:[dic objectForKey:@"kind"]]) {
                    NSString *str = [dic objectForKey:@"kind"];
                    [[[self.carValueArr lastObject] objectForKey:str] addObject:car];
                    
                } else {
                    NSMutableArray *carArr = [NSMutableArray arrayWithObject:car];
                    NSMutableDictionary *carDic = [NSMutableDictionary dictionaryWithObject:carArr forKey:[dic objectForKey:@"kind"]];
                    [self.carValueArr addObject:carDic];
                }
                
                
            }
            
            [self.exactTable reloadData];
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 120, 280, 100)];
            
            imageView.image = [UIImage imageNamed:@"poNet.jpg"];
            
            self.tableView.backgroundView = imageView;
            
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起暂无网络" message:@"请返回" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil];
            [alertView show];
        }];
    if (self.exactTable.hidden == YES) {
        [UIView animateWithDuration:0.5 animations:^{
            [self exactTableShow];
        }];
        
    }
}
// 非热门
- (void)startCarValueConnectionwithUrl:(NSString *)url
{
    
    AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
    
    [manager1.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    
    [manager1 GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSArray *arr = [responseObject objectForKey:@"manufacturers"];
        for (NSDictionary *dic in arr) {
            NSMutableArray *serialsArr = [NSMutableArray array];
            
            for (NSDictionary *carDic in [dic objectForKey:@"serials"]) {
                ExaxtCar *car = [[ExaxtCar alloc]initWithDictionary:carDic];
                [serialsArr addObject:car];
                [car release];
            }
            NSDictionary *nameDic = [NSDictionary dictionaryWithObject:serialsArr forKey:[dic objectForKey:@"name"]]; // 以车牌为key值的字典  如一汽奥迪
            [self.carValueArr addObject:nameDic];
            
        }
        
        [self.exactTable reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 120, 280, 100)];
        
        imageView.image = [UIImage imageNamed:@"poNet.jpg"];
        
        self.tableView.backgroundView = imageView;
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起暂无网络" message:@"请检查网络设置" delegate:self cancelButtonTitle:@"请返回" otherButtonTitles:nil, nil];
        [alertView show];
    }];
    if (self.exactTable.hidden == YES) {
        [self exactTableShow];
    }
    
}

- (void)exactTableShow
{
    self.switchButton.hidden = NO;
    self.exactTable.hidden = NO;
    self.switchButton.frame =  CGRectMake(self.view.frame.size.width / 4 , 140, 20, 30);
    self.exactTable.frame = CGRectMake(self.view.bounds.size.width / 4  , 0, self.view.bounds.size.width / 4 * 3, self.view.bounds.size.height - 64 );
}
#pragma mark 加载视图
- (void)setupSubViews
{
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"sousuo.png"] style:(UIBarButtonItemStylePlain) target:self action:@selector(leftItemAction:)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"gerenzhongxin.png"] style:(UIBarButtonItemStyleDone) target:self action:@selector(rightItemAction:)];
   
    // segment
    self.navigationController.navigationBar.translucent = NO;
    self.segment = [[UISegmentedControl alloc]initWithItems:@[@"品牌选车",@"精准选车"]];
    self.segment.frame = CGRectMake(0, 0, self.view.bounds.size.width, 40);
    [self.segment addTarget:self action:@selector(segmentAction:) forControlEvents:(UIControlEventValueChanged)];
    // 更改segment的样式
    [self.segment setBackgroundImage:[UIImage imageNamed:@"segment0.jpg"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    [self.segment setBackgroundImage:[UIImage imageNamed:@"segment.jpg"] forState:UIControlStateSelected barMetrics:UIBarMetricsDefault];
    [self.segment setDividerImage:[UIImage imageNamed:@"segment1.jpg"] forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    NSDictionary *colorAttr = [NSDictionary dictionaryWithObject:[UIColor grayColor] forKey:UITextAttributeTextColor];
    [self.segment setTitleTextAttributes:colorAttr forState:UIControlStateNormal];
    NSDictionary *colorAttr1 = [NSDictionary dictionaryWithObject:[WebColor dodgerBlue] forKey:UITextAttributeTextColor];
    [self.segment setTitleTextAttributes:colorAttr1 forState:UIControlStateSelected];
    [self.view addSubview:self.segment];
    
    // scrollView
    self.scrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 40, self.view.bounds.size.width , self.view.bounds.size.height - 64)];
    self.scrollView.delegate = self;
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.contentSize = CGSizeMake(self.view.bounds.size.width * 2, 0);
    [self.view addSubview:self.scrollView];
    
    // tableview品牌
    
    
    self.segment.selectedSegmentIndex = 0;
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width - 20, self.view.bounds.size.height - 64 - 40 - 49) style:(UITableViewStylePlain)];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[BrandCarCell class] forCellReuseIdentifier:@"seek"];
    [self.tableView registerClass:[HotCell class] forCellReuseIdentifier:@"hot"];
    
    [self.scrollView addSubview:self.tableView];
    // tableView价格
    self.exactTable = [[UITableView alloc]initWithFrame:CGRectMake(self.view.bounds.size.width / 4 * 5, 0, self.view.bounds.size.width / 4 * 3, self.view.bounds.size.height  - 49 ) style:(UITableViewStylePlain)];
    self.exactTable.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.exactTable registerClass:[CarValueCell class] forCellReuseIdentifier:@"value"];
    self.exactTable.hidden = YES;
    self.exactTable.delegate = self;
    self.exactTable.dataSource = self;
    [self.scrollView addSubview:self.exactTable];
    // button开关
    self.switchButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    //[self.switchButton addSubview:self.scrollView];
    [self.switchButton setFrame:CGRectMake(self.view.frame.size.width , 140, 20, 30)];
    [self.switchButton setBackgroundImage:[UIImage imageNamed:@"shouqi.png"] forState:(UIControlStateNormal)];
    [self.scrollView addSubview:self.switchButton];
    self.switchButton.hidden = YES;
    [self.switchButton addTarget:self action:@selector(buttonClicked:) forControlEvents:(UIControlEventTouchUpInside)];
    
    // collectionView
    self.passButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    
    self.passButton.frame = CGRectMake(10 + self.view.bounds.size.width, 340, self.view.bounds.size.width - 20, 30);
    
    
    [self.passButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
    
    [self.scrollView  addSubview:self.passButton];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.itemSize = CGSizeMake(95, 40);
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = 2;
    flowLayout.minimumLineSpacing = 15;
    // 整个section 的布局 距离边界的距离（上  左 下 右）
    flowLayout.sectionInset = UIEdgeInsetsMake(5, 5, 5, 5);
    flowLayout.headerReferenceSize = CGSizeMake(self.view.frame.size.width, 25);
    
    self.collectionView.allowsSelection = YES;
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(self.view.bounds.size.width , 0, self.view.bounds.size.width , self.view.bounds.size.height - 64 - 40 - 49 - 30) collectionViewLayout:flowLayout];
    self.scrollView.bounces = NO;
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    [self.collectionView registerClass:[MySecion class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader  withReuseIdentifier:@"section"];
    [self.collectionView registerClass:[CollectionCell class] forCellWithReuseIdentifier:@"cell"];
    
    [self.scrollView addSubview:self.collectionView];
    // button
    
    
    [flowLayout release];
    [_collectionView release];
    [_segment   release];
    [_indexBar  release];
    [_tableView release];
    [_scrollView release];
    [_exactTable release];
    
}


#pragma buttonClicked
- (void)buttonClicked:(UIButton *)button
{
    button.frame = CGRectMake(self.view.frame.size.width , 140, self.view.frame.size.width, 30);
    button.hidden = YES;
    self.exactTable.frame = CGRectMake(self.view.bounds.size.width / 4 * 5, 0, self.view.bounds.size.width / 4 * 3, self.view.bounds.size.height  - 49 );
    self.exactTable.hidden = YES;
}
#pragma mark segment点击方法


- (void)segmentAction:(UISegmentedControl *)segment
{
    
    self.scrollView.contentOffset = CGPointMake(self.view.bounds.size.width * segment.selectedSegmentIndex, 0);
}
- (void)leftItemAction:(UIBarButtonItem *)barButton
{
    SearchViewController *searchVC = [[SearchViewController alloc]init];
    [self.navigationController pushViewController:searchVC animated:YES];
    [searchVC release];
    
}
- (void)rightItemAction:(UIBarButtonItem *)barButton
{
    MineViewController *mineVC = [[MineViewController alloc]init];
    [self.navigationController pushViewController:mineVC animated:YES];
    [mineVC release];
    
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - collection协议
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    
    return self.collectionSection.count;
    
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    NSString *str = self.collectionSection[section];
    NSArray *arr = [self.collectionClass[section] objectForKey:str];
    
    return arr.count;
}
// section
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    MySecion *section = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"section" forIndexPath:indexPath];
    section.backgroundColor = [WebColor whiteSmoke];
    section.secionName.textColor = [WebColor dimGray];
    section.secionName.textAlignment = 1;
    section.secionName.font = [UIFont systemFontOfSize:14];
    section.secionName.text = self.collectionSection[indexPath.section];
    return section;
}
// collectionCell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    CollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    cell.layer.borderWidth = 1;
    cell.cellLabel.textColor = [UIColor grayColor];
    cell.layer.borderColor = [UIColor lightGrayColor].CGColor;
    NSString *str = self.collectionSection[indexPath.section];
    MyCar *myCar = [self.collectionClass[indexPath.section] valueForKey:str][indexPath.item];
    cell.cellLabel.text = myCar.name;
    //[self ChangeColorWithIndexPath:indexPath];
    [self ChangeColor];
    
    cell.selected = YES;
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 60)];
    imageView.image = [UIImage imageNamed:@"cellbg.jpg"];
    cell.backgroundView = imageView;
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSIndexPath *index = self.collectionIndexPathArr[indexPath.section];
    
    NSString *str = self.collectionSection[indexPath.section];
    
    MyCar *myCar = [self.collectionClass[indexPath.section] valueForKey:str][indexPath.item];
    [self.valueArr replaceObjectAtIndex:indexPath.section withObject:myCar.value];
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v2/price/models/search?price=%@&jb=%@&pl%@&bsx=%@&pageNo=1&pageSize=20&v=4.3.0", self.valueArr[0], self.valueArr[1], self.valueArr[2], self.valueArr[3] ];
    [self connectionExactCarWithUrl:strUrl];
    
    if (indexPath.item != index.item) {
        
        
        CollectionCell *cellFirst = (CollectionCell *)[collectionView cellForItemAtIndexPath:index];
        cellFirst.cellLabel.textColor = [UIColor grayColor];
        cellFirst.layer.borderColor = [UIColor lightGrayColor].CGColor;
        
    }
    [self.collectionIndexPathArr replaceObjectAtIndex:indexPath.section withObject:indexPath];
    
    [self ChangeColor];
    
    
    
    
    
    
    
}
#pragma mark - 解析有多少款符合条件的车
- (void)connectionExactCarWithUrl:(NSString *)url
{
    AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
    [manager1.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
    [manager1 GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        self.modelArr = [responseObject objectForKey:@"data"];
        self.modelTotal = [responseObject objectForKey:@"total"];
        
        if ([self.modelTotal isEqual:@0]) {
            [self.passButton setTitle:[NSString stringWithFormat:@"%@款车符合条件，请重新选择", self.modelTotal] forState:UIControlStateNormal];
            self.passButton.backgroundColor = [UIColor lightGrayColor];
            
        } else {
            self.passButton.backgroundColor = [UIColor blueColor];
            
            [self.passButton setTitle:[NSString stringWithFormat:@"%@款车符合条件，点击查看", self.modelTotal] forState:UIControlStateNormal];
            [self.passButton addTarget:self action:@selector(passButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
        }

        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 120, 280, 100)];
        imageView.image = [UIImage imageNamed:@"poNet.jpg"];
        self.tableView.backgroundView = imageView;
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起暂无网络" message:@"请返回" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil];
        [alertView show];
    }];

    [self.scrollView bringSubviewToFront:self.passButton];
}

- (void)passButtonAction:(UIButton *)button
{
    if ([[button currentTitle] hasPrefix:@"0"]) {
        
        
    } else {
        
        ExactCarController *exactVC = [[ExactCarController alloc]init];
        exactVC.arr = self.modelArr;
        [self.navigationController pushViewController:exactVC animated:YES];
        [exactVC release];
    }
    
}
- (void)collectionView:(UICollectionView *)collectionView didDeselectItemAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    CollectionCell *cell = (CollectionCell *) [collectionView cellForItemAtIndexPath:indexPath];
    cell.cellLabel.textColor = [UIColor grayColor];
    cell.layer.borderColor = [UIColor grayColor].CGColor;
    
}



- (void)ChangeColor
{
    
    for (int i = 0; i < 4; i++) {
        CollectionCell *cell = (CollectionCell *) [self.collectionView cellForItemAtIndexPath:self.collectionIndexPathArr[i]];
        cell.cellLabel.textColor = [UIColor blueColor];
        cell.layer.borderColor = [UIColor blueColor].CGColor;
        
    }
    
    
    
}
#pragma mark - scrollView协议




- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    self.segment.selectedSegmentIndex = self.scrollView.contentOffset.x / self.view.bounds.size.width;
}
#pragma mark - AIM协议
- (void)tableViewIndexBar:(AIMTableViewIndexBar *)indexBar didSelectSectionAtIndex:(NSInteger)index
{
    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    if (scrollView == self.tableView) {
        self.switchButton.frame = CGRectMake(self.view.frame.size.width , 140, 20, 30);
        self.switchButton.hidden = YES;
        self.exactTable.frame = CGRectMake(self.view.bounds.size.width / 4 * 5, 0, self.view.bounds.size.width / 4 * 3, self.view.bounds.size.height  - 49 );
        self.exactTable.hidden = YES;
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    NSDictionary *attributes=[NSDictionary dictionaryWithObjectsAndKeys:[UIColor whiteColor],NSForegroundColorAttributeName,[UIFont boldSystemFontOfSize:20],NSFontAttributeName, nil];
    [self.navigationController.navigationBar setTitleTextAttributes:attributes];
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbackground.jpg"] forBarMetrics:UIBarMetricsDefault];

}
/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
